package {
import flash.events.TimerEvent;
import flash.events.Event;
import flash.utils.Timer;

import org.flixel.*;

public class Spider extends FlxSprite {
	
	[Embed(source="data/SpiderWalk&Egg01.png")] private var sprite:Class;
	
	private var changeDirectionTimer:Timer;
	private var layEggTimer:Timer;
	private var _layingEgg:Boolean = false; // (state)
	private var direction:int;
	
	private var _web:PlayState;
	
	public function Spider ($environment:PlayState, X:int, Y:int)
	{
		super(X, Y);
		
		_web = $environment;
		
		loadGraphic(sprite, true);
		//offset = new FlxPoint(frameWidth/2, frameHeight/2);
		//x -= frameWidth / 2;
		//y -= frameHeight / 2;
		
		addAnimation("walk", [0,1,2,3], 4,true);
		direction = (Math.random()*3)+1;
		changeDirectionTimer = new Timer(2000);
		changeDirectionTimer.addEventListener(TimerEvent.TIMER, changeDirection);
		changeDirectionTimer.start();
		
		layEggTimer = new Timer(2000);
		layEggTimer.addEventListener(TimerEvent.TIMER, layEgg);
		layEggTimer.start();
		
		addAnimation('walking', [1,2,3,4,5], 24);
		addAnimation('laying', [6, 7, 8, 9, 10, 11, 12], 24, false);
		addAnimationCallback(changeState);
		play('walking');
		thrust = 100;
		this.direction
	}
	
	override public function update ():void
	{
		super.update();
		if (!_layingEgg)
			move(direction);
	}
	
	private function changeState ($name:String, $frameNumber:uint, $frameIndex:uint):void {
		if ($name == 'laying' && finished) {
			FlxG.log(this);
			_layingEgg = false;
			play('walking');
			//FlxU.rotatePoint();
			_web.add(new Egg(x , y ));
		}
	}
	private function changeDirection (e:TimerEvent):void
	{
		if(x > 700)
			direction = 4;
		else if(x < 100)
			direction = 2;
		else if(y > 500)
			direction = 1;
		else if(y < 100)
			direction = 3
		else 
			direction = (Math.random()*3)+1;
	}
	
	private function layEgg (e:TimerEvent):void
	{
		play('laying');
		velocity.x *= .01;
		velocity.y *= .01;
		_layingEgg = true;
	}
	
	private function move ($direction:int):void {
		switch($direction){
			case 1:
				angle = 90;
				break;
			case 2:
				angle = 180;
				break;
			case 3:
				angle = 0;
				break;
			case 4:
				angle = 270;
				break;
		}
	}
	
}

}